package com.smedi.ismedi.inmail.core.port.adapter.service.impl;

import com.smedi.ismedi.inmail.core.domain.dto.OrganizationQuery;
import com.smedi.ismedi.inmail.core.port.adapter.convert.AdapterConverter;
import com.smedi.ismedi.inmail.core.port.adapter.service.OrganizationRemoteService;
import com.smedi.ismedi.organization.api.dto.request.OrganizationListQueryRequest;
import com.smedi.ismedi.organization.api.dto.response.resp.AllOrganizationResp;
import com.smedi.ismedi.organization.api.dto.response.resp.OrganizationResp;
import com.smedi.ismedi.organization.api.feign.RemoteHrOrganizationFeignApi;
import com.smedi.ismedi.web.starter.common.ResponseData;
import com.smedi.ismedi.web.starter.exception.BasicError;
import com.smedi.ismedi.web.starter.exception.LogicException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class OrganizationRemoteServiceImpl implements OrganizationRemoteService {


    private final RemoteHrOrganizationFeignApi remoteHrOrganizationFeignApi;
    private final AdapterConverter adapterConverter;


    @Override
    public OrganizationResp getOrganizationOne(OrganizationQuery organizationQuery) {
        return null;
    }

    @Override
    public List<OrganizationResp> getOrganizationList(OrganizationQuery organizationQuery) {
        OrganizationListQueryRequest organizationListQueryRequest = adapterConverter.organizationQueryToOrganizationListQueryRequest(organizationQuery);
        ResponseData<List<OrganizationResp>> responseData = remoteHrOrganizationFeignApi.getOrganizationList(organizationListQueryRequest);
        if (!responseData.isSuccess()) {
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
        return responseData.getData();
    }

    @Override
    public List<AllOrganizationResp> getOrganizationList(List<Long> ids) {
        ResponseData<List<AllOrganizationResp>> responseData = remoteHrOrganizationFeignApi.getOrgResponseData(ids);
        if(!responseData.isSuccess()){
            throw LogicException.raise(BasicError.CALL_REMOTE_API_ERROR, responseData.getApplication(), String.valueOf(responseData.getErrorMsg()));
        }
        if(CollectionUtils.isEmpty(responseData.getData())){
            return new ArrayList<>();
        }
        List<AllOrganizationResp> allorgs = responseData.getData().stream().filter(allOrganizationResp -> allOrganizationResp.getType().equals("PROJECT_MANAGEMENT_ORGANIZATION")).sorted(Comparator.comparing(AllOrganizationResp::getDisplayOrder)).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(allorgs)){
            return new ArrayList<>();
        }
        return allorgs;
    }
}
